// 假设后端返回的公钥是 Base64 格式
const publicKeyBase64 = "YOUR_PUBLIC_KEY_BASE64";

// 将 Base64 转换为 PEM 格式
const publicKeyPem = `-----BEGIN PUBLIC KEY-----\n${publicKeyBase64}\n-----END PUBLIC KEY-----`;

// 使用 crypto.subtle 导入公钥并加密数据
async function encryptWithPublicKey(message) {
    const encoder = new TextEncoder();
    const data = encoder.encode(message);

    // 导入公钥
    const publicKey = await crypto.subtle.importKey(
        "spki",
        base64ToArrayBuffer(publicKeyBase64),
        { name: "RSA-OAEP", hash: "SHA-256" },
        true,
        ["encrypt"]
    );

    // 加密数据
    const encryptedData = await crypto.subtle.encrypt(
        { name: "RSA-OAEP" },
        publicKey,
        data
    );

    // 将加密后的数据转换为 Base64
    return arrayBufferToBase64(encryptedData);
}

// 辅助函数：将 Base64 转换为 ArrayBuffer
function base64ToArrayBuffer(base64) {
    const binaryString = atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

// 辅助函数：将 ArrayBuffer 转换为 Base64
function arrayBufferToBase64(buffer) {
    let binary = "";
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}

// 测试加密
(async () => {
    const encryptedMessage = await encryptWithPublicKey("Hello, World!");
    console.log("Encrypted Message:", encryptedMessage);
})();